<?php

namespace Utuo\Pay\Driver;

class Wxtenpay extends \Utuo\Pay\Pay {
	
	protected $config = array();
	
	public function check() {
		if (!$this->config['paySignKey'] || !$this->config['partnerId'] || !$this->config['partnerKey']) {
			E("微信支付设置有误！");
		}
		return true;
	}
	
	public function buildRequestForm(\Utuo\Pay\PayVo $vo) {
		$package = array(
			'bank_type' => 'WX',
			'fee_type' => 1,
			'input_charset' => "UTF-8",
			'body' => $vo->getBody(),
			'notify_url' => $this->config['notify_url'],
			'partner' => $this->config['partnerId'],
			'out_trade_no' => $vo->getOrderNo(),
			'total_fee' => floor($vo->getFee() * 100),
			'spbill_create_ip' => get_client_ip()
		);
		
		$packageStr = '';
		foreach ( $package as $key => $value  ) {
			empty($value) or $packageStr .= "{$key}=".urlencode($value)."&";
		}
		$packageStr .= 'sign='.$this->createSign($package);
		
		$param = array(
			'appId' => $this->config['appid'],
			'timeStamp' => time(),
			'nonceStr' => md5(time().rand(9999, 9999)),
			'package' => $packageStr,
			'appkey' => $this->config['paySignKey'],
		);
		$paySignStr = '';
		ksort($param);
		reset($param);
		foreach ( $param as $key => $value) {
			$paySignStr .= strtolower($key)."=".$value."&";
		}
		unset($param['appkey']);
		$param['paySign'] = sha1(substr($paySignStr, 0, -1));
		$param['signType'] = 'SHA1';
		
		$sHtml = $this->_buildForm($param, $this->gateway);
		
		return $sHtml;
	}

	public function verifyNotify( $notify ) {
		$notify['appkey'] = $this->config['paySignKey'];
		$appSignature = $notify['AppSignature'];
		unset( $notify['AppSignature'] );
		$str = '';
		ksort($notify);
		reset($notify);
		foreach ( $notify as $key => $value) {
			$str .= strtolower($key)."=".$value."&";
		}
		if ( sha1(substr($str, 0, -1)) == $appSignature ) {
			return true;
		}
		return false;
	}
	
	/**
	 * 构造表单
	 */
	protected function _buildForm($params, $gateway, $method = 'post', $charset = 'utf-8') {
		header("Content-type:text/html;charset={$charset}");
		$Html = <<<TAG
<script>
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
	WeixinJSBridge.invoke('getBrandWCPayRequest',{
		"appId":"{$params['appId']}", "timeStamp":"{$params['timeStamp']}",
		"nonceStr":"{$params['nonceStr']}","package":"{$params['package']}",
		"signType":"{$params['signType']}",
		"paySign":"{$params['paySign']}"
	},function(res){
		//返回res.err_msg,取值
		//get_brand_wcpay_request:cancel用户取消
		//get_brand_wcpay_request:fail发送失败
		//get_brand_wcpay_request:ok发送成功
		WeixinJSBridge.log(res.err_msg);
		alert(res.err_msg);
		alert(res.err_code+''+res.err_desc);
	});
});
</script>
TAG;
		return $Html;
	}
	
	
    /**
     * 创建签名
     * @param type $params
     */
    protected function createSign($params) {
        ksort($params);
        reset($params);
        
        $arg = '';
        foreach ($params as $key => $value) {
           empty($value) or $arg .= "{$key}={$value}&";
        }
        return strtoupper(md5($arg . 'key=' . $this->config['partnerKey']));
    }
	
}